package cn.gxa.edu_adm.servlet;

import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "DownLoadStudentModelServlet",urlPatterns = "/downLoadStudentModel")
public class DownLoadStudentModelServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得用户要下载的文件的路径
        String  filePath=request.getParameter("filePath");
        //获得文件名字
        String  fileName= FilenameUtils.getName(filePath);
        //获得文件的绝对路径
        String  absolutePath=getServletContext().getRealPath(filePath);
        //把文件响应给前端 io
        //设置响应的方式
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        //边读边写 获取流
        BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(absolutePath));
        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(response.getOutputStream());
        //边读边写
        int i;
        while((i=bufferedInputStream.read())!=-1){
            bufferedOutputStream.write(i);
        }

        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        bufferedInputStream.close();
    }
}
